package com.robot.admin.controller;

import com.alibaba.fastjson.JSON;
import com.robot.admin.client.MemberClient;
import com.robot.admin.client.MerchantClient;
import com.robot.admin.client.OrdersClient;
import com.robot.admin.pojo.Admin;
import com.robot.admin.pojo.client.Store;
import com.robot.admin.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;
import util.UpdateUtil;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/store")
public class StoreController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private MerchantClient merchantClient;
    @Autowired
    private MemberClient memberClient;
    @Autowired
    private OrdersClient ordersClient;

    @Autowired
    private CheckUtil checkUtil;
    @Autowired
    private BCryptPasswordEncoder encoder;
    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 店铺列表并分页
     *
     * @param page
     * @param size
     * @return
     */
    @PostMapping(value = "{page}/{size}", produces = "application/json; charset=utf-8")
    public Result findStores(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(merchantClient.thirdFindStores(searchMap, page, size)));
    }

    /**
     * 店铺详情
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/{id}")
    public Result findStoreById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        Admin adminInDb = adminService.findById(claims.getId());
        logger.info("adminInDb=" + adminInDb);
        if (adminInDb == null) {
            return new Result(StatusCode.ERROR_ADMIN_DOES_NOTE_EXIST);
        }

        //商家信息
        Store storeInDb = JSON.parseObject(merchantClient.thirdFindStoreById(id), Store.class);
        logger.info("storeInDb=" + storeInDb);
        if (storeInDb == null) {
            return new Result(StatusCode.ERROR_MERCHANT_DOES_NOTE_EXIST);
        }
        if (storeInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR, "商家已被删除");
        }

        //累计消费金额
        String ordersPayAmount = JSON.parseObject(ordersClient.thirdFindSubOrderPayAmountByStoreId(id), String.class);
        //本月累计支付成功的订单数
        String thisMonthOrdersCount = JSON.parseObject(ordersClient.thirdFindSubOrderThisMonthCountByStoreId(id), String.class);
        //剩余余额
        String balance = JSON.parseObject(ordersClient.thirdFindPurchaseBalanceByStoreId(id), String.class);


        HashMap<String, Object> map = new HashMap<>(2);
        map.put("store", storeInDb);
        map.put("ordersPayAmount", ordersPayAmount);
        map.put("thisMonthOrdersCount", thisMonthOrdersCount);
        map.put("balance", balance);
        return new Result(StatusCode.SUCCESS_QUERY, map);
    }

    /**
     * 修改店铺
     *
     * @param store
     * @param id
     */
    @PutMapping(value = "{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result updateStore(@RequestBody Store store, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        Admin adminInDb = adminService.findById(claims.getId());
        logger.info("adminInDb=" + adminInDb);
        if (adminInDb == null) {
            return new Result(StatusCode.ERROR_ADMIN_DOES_NOTE_EXIST);
        }

        if (!checkUtil.checkPhone(store.getPhone())) {
            return new Result(StatusCode.ERROR_INVALID_PHONE);
        }
        if (checkUtil.checkEmail(store.getEmail())) {
            return new Result(StatusCode.ERROR_INVALID_EMAIL);
        }
        if (store.getCoverImage() != null && !"".equals(store.getCoverImage())) {

            if (!checkUtil.checkImage(store.getCoverImage())) {
                return new Result(StatusCode.ERROR_COVER_IMAGE_REQUIRED);
            }
        }
        if (store.getImages() != null && !"".equals(store.getImages())) {
            Map<String, Object> map = checkUtil.checkImages(store.getImages());
            Boolean flag = (Boolean) map.get("flag");
            if (!flag) {
                return new Result(StatusCode.ERROR_FILE_FORMAT, (String) map.get("message"));
            } else {
                store.setImages((String) map.get("message"));
            }
        }
        if (store.getBusinessLicenseImg() != null && !"".equals(store.getBusinessLicenseImg())) {

            if (!checkUtil.checkImage(store.getBusinessLicenseImg())) {
                return new Result(StatusCode.ERROR_FILE_FORMAT, "请上传正确格式的营业执照照片");
            }

        }
        if (store.getIdCardFront() != null && !"".equals(store.getIdCardFront())) {
            if (!checkUtil.checkImage(store.getIdCardFront())) {
                return new Result(StatusCode.ERROR_ID_CARD_FRONT_REQUIRED);
            }

        }
        if (store.getIdCardBack() != null && !"".equals(store.getIdCardBack())) {

            if (!checkUtil.checkImage(store.getIdCardBack())) {
                return new Result(StatusCode.ERROR_FILE_FORMAT, "请上传正确格式的法人身份证个人页");
            }
        }
        if (store.getPassword() != null && !"".equals(store.getPassword())) {
            store.setPassword(encoder.encode(store.getPassword()));
        }

        Store storeInDb = JSON.parseObject(merchantClient.thirdFindStoreById(id), Store.class);
        if (storeInDb == null) {
            return new Result(StatusCode.ERROR_MERCHANT_DOES_NOTE_EXIST);
        }
        store.setId(id);
        UpdateUtil.copyNonNullProperties(store, storeInDb);
        merchantClient.thirdUpdateStore(JSON.toJSONString(storeInDb));
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 启用禁用/上下架店铺
     *
     * @param store
     * @param id
     */
    @PutMapping(value = "updateStoreStatus/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result updateStoreStatus(@RequestBody Store store, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        Admin adminInDb = adminService.findById(claims.getId());
        logger.info("adminInDb=" + adminInDb);
        if (adminInDb == null) {
            return new Result(StatusCode.ERROR_ADMIN_DOES_NOTE_EXIST);
        }

        String status = store.getStatus();
        logger.info("status=" + status);
        if (status == null || "".equals(status)) {
            return new Result(StatusCode.ERROR, "上下架状态必填");
        }
        /**
         * store表status 状态 0禁用1启用
         */
        String storeStatusForbidden = "0";
        String storeStatusEnable = "1";
        if (!storeStatusForbidden.equals(status) && !storeStatusEnable.equals(status)) {
            return new Result(StatusCode.ERROR, "上下架状态错误");
        }

        Store storeInDb = JSON.parseObject(merchantClient.thirdFindStoreById(id), Store.class);
        logger.info("storeInDb=" + storeInDb);
        if (storeInDb == null) {
            return new Result(StatusCode.ERROR_MERCHANT_DOES_NOTE_EXIST);
        }
        storeInDb.setStatus(status);
        merchantClient.thirdUpdateStore(JSON.toJSONString(storeInDb));
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 删除店铺
     *
     * @param id
     */
    @PutMapping(value = "deleteStore/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result deleteStore(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        Admin adminInDb = adminService.findById(claims.getId());
        logger.info("adminInDb=" + adminInDb);
        if (adminInDb == null) {
            return new Result(StatusCode.ERROR_ADMIN_DOES_NOTE_EXIST);
        }

        Store storeInDb = JSON.parseObject(merchantClient.thirdFindStoreById(id), Store.class);
        logger.info("storeInDb=" + storeInDb);
        if (storeInDb == null) {
            return new Result(StatusCode.ERROR_MERCHANT_DOES_NOTE_EXIST);
        }

        storeInDb.setDeletedAt(LocalDateTime.now());
        merchantClient.thirdUpdateStore(JSON.toJSONString(storeInDb));
        return new Result(StatusCode.SUCCESS_DELETED);
    }
}
